

import sys
from time import sleep
import os, time, uuid, hashlib, configparser, subprocess, re, shutil


def get_lsusb_output():
    """Run the lsusb command and return its output."""
    result = subprocess.run(['lsusb'], stdout=subprocess.PIPE, text=True)
    return result.stdout

def parse_lsusb_output(output):
    """Parse the lsusb output and return a list of keyboard devices."""
    keyboards = []
    for line in output.splitlines():
        # Convert line to lower case for case-insensitive matching
        if 'keyboard' in line.lower():
            keyboards.append(line)
            
        # Check for 2.4G wireless keyboards
        if '2.4g' in line.lower():
            keyboards.append(line)
    return keyboards

def system_reboot():
    try:
        # Execute the reboot command
        result = subprocess.run(['reboot'], check=True)
        print("System is rebooting...")
    except subprocess.CalledProcessError as e:
        print(f"Failed to reboot: {e}")

if __name__ == '__main__':

    while True:  
        lsusb_output = get_lsusb_output()
        keyboards = parse_lsusb_output(lsusb_output)
        
        if keyboards:
            print("Detected keyboard devices:")            
            for keyboard in keyboards:
                print(keyboard)

            print("prepare reboot...")                
            system_reboot()

        else:
            print("No keyboard devices detected.")
          
        # 检查是否打开系统设置界面
        subprocess.run(['bash', '/usr/local/bin/bj2/check_gnome_setting.sh'])        
        
        lsusb_output = get_lsusb_output()
        keyboards = parse_lsusb_output(lsusb_output)

        time.sleep(1)
